﻿#include "LabelList.h"
#include <QMouseEvent>
#include <QPainter>
#include <QScrollBar>
#include <QPropertyAnimation>
#include <QtGlobal>
#include "Defs.h"
#include <QRegularExpression>
#include <QInputDialog>
#include <qmenu.h>
#include <QMessageBox>

LabelItem::LabelItem(const QString& name, int row, QWidget* parent)
    : QWidget(parent), m_isHovered(false)
{
    setupUI();
    setName(name);
    setRowNumber(row);

    connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged, this, &LabelItem::onThemeChanged);

    // 根据当前主题初始化样式
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
    if (currentTheme == ThemeManager::Theme::Dark) {
        setDarkTheme();
    }
    else {
        setLightTheme();
    }
}

LabelItem::LabelItem(const QString& name, const QString& rowStr, QWidget* parent)
    : QWidget(parent), m_isHovered(false)
{
    setupUI();
    setName(name);
    setRowNumber(rowStr);

    connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged, this, &LabelItem::onThemeChanged);

    // 根据当前主题初始化样式
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
    if (currentTheme == ThemeManager::Theme::Dark) {
        setDarkTheme();
    }
    else {
        setLightTheme();
    }
}

void LabelItem::setDarkTheme()
{
    // 直接在stylesheet中设置颜色
    m_nameLabel->setStyleSheet("color: #D4D4D4; background-color: transparent;");
    m_rowLabel->setStyleSheet("color: #858585; background-color: transparent;");

    // 设置删除按钮样式
    m_deleteBtn->setStyleSheet(R"(
        QPushButton {
            background-color: transparent;
            border: none;
            color: #858585;
            font-size: 16px;
            font-weight: bold;
            border-radius: 10px;
        }
        QPushButton:hover {
            background-color: #FF5252;
            color: #FFFFFF;
        }
    )");

    // 设置右键菜单深色主题
    m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #252526;
            border: 1px solid #3E3E42;
            border-radius: 6px;
            padding: 4px;
            color: #D4D4D4;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #094771;
            color: #FFFFFF;
        }
        QMenu::item:disabled {
            color: #858585;
        }
        QMenu::separator {
            height: 1px;
            background-color: #3E3E42;
            margin: 4px 8px;
        }
    )");

    update();
}

void LabelItem::setLightTheme()
{
    // 使用正确的浅色主题颜色
    m_nameLabel->setStyleSheet("color: #2C3E50; background-color: transparent;");
    m_rowLabel->setStyleSheet("color: #7F8C8D; background-color: transparent;");

    // 设置删除按钮样式
    m_deleteBtn->setStyleSheet(R"(
        QPushButton {
            background-color: transparent;
            border: none;
            color: #95A5A6;
            font-size: 16px;
            font-weight: bold;
            border-radius: 10px;
        }
        QPushButton:hover {
            background-color: #FF5252;
            color: #FFFFFF;
        }
    )");

    // 设置右键菜单浅色主题
    m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #FFFFFF;
            border: 1px solid #E1E5E9;
            border-radius: 6px;
            padding: 4px;
            color: #495057;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #E7F3FF;
            color: #4A90E2;
        }
        QMenu::item:disabled {
            color: #ADB5BD;
        }
        QMenu::separator {
            height: 1px;
            background-color: #E9ECEF;
            margin: 4px 8px;
        }
    )");

    update();
}


void LabelItem::setName(const QString& name) {
    m_fullName = name;
    this->setToolTip(name);  // 设置 tooltip
    update();  // 触发重绘
}

void LabelItem::setRowNumber(int row)
{
    m_rowLabel->setText("行: " + QString::number(row));
}

void LabelItem::setRowNumber(const QString& rowStr)
{
    m_rowLabel->setText("行: " + rowStr);
}

void LabelItem::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        // 提取 "行: 123" 中的数字部分
        QString text = m_rowLabel->text();
        int row = 0;

        QRegularExpression re("\\d+");  // 匹配数字
        QRegularExpressionMatch match = re.match(text);
        if (match.hasMatch()) {
            row = match.captured(0).toInt();
        }

        qDebug() << "LabelItem 点击，跳转到行:" << row;
        emit clicked(row);
    }
    QWidget::mousePressEvent(event);
}

void LabelItem::contextMenuEvent(QContextMenuEvent* event)
{
    m_contextMenu->exec(event->globalPos());
}

#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
void LabelItem::enterEvent(QEvent* event)
#else
void LabelItem::enterEvent(QEnterEvent* event)
#endif
{
    m_isHovered = true;
    m_deleteBtn->show();  // 鼠标进入时显示删除按钮
    update();  // 触发重绘
    QWidget::enterEvent(event);
}

void LabelItem::leaveEvent(QEvent* event)
{
    m_isHovered = false;
    m_deleteBtn->hide();  // 鼠标离开时隐藏删除按钮
    update();  // 触发重绘
    QWidget::leaveEvent(event);
}

void LabelItem::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();

    // 先绘制悬浮背景
    if (m_isHovered) {
        if (currentTheme == ThemeManager::Theme::Dark) {
            painter.setBrush(QColor(62, 62, 66));
        }
        else {
            painter.setBrush(QColor(232, 244, 253));
        }
        painter.setPen(Qt::NoPen);
        painter.drawRoundedRect(rect(), 6, 6);
    }

    // 再绘制边框
    painter.setBrush(Qt::NoBrush);
    if (currentTheme == ThemeManager::Theme::Dark) {
        painter.setPen(QPen(QColor("#ACC2C8"), 1));
    }
    else {
        painter.setPen(QPen(QColor("#E1E5E9"), 1));
    }
    painter.drawRoundedRect(rect().adjusted(0, 0, -1, -1), 6, 6);

    // 绘制省略的标签名称
    if (!m_fullName.isEmpty()) {
        QRect nameLabelRect = m_nameLabel->geometry();

        // 设置文本颜色
        if (currentTheme == ThemeManager::Theme::Dark) {
            painter.setPen(QColor("#D4D4D4"));
        }
        else {
            painter.setPen(QColor("#2C3E50"));
        }

        // 设置字体
        painter.setFont(m_nameLabel->font());

        // 使用 QFontMetrics 计算省略文本
        QFontMetrics metrics(m_nameLabel->font());
        QString elidedText = metrics.elidedText(
            m_fullName,
            Qt::ElideRight,
            nameLabelRect.width()
        );

        // 绘制省略文本
        painter.drawText(nameLabelRect, Qt::AlignLeft | Qt::AlignVCenter, elidedText);
    }

    // 调用基类 paintEvent，让其他子控件正确绘制
    QWidget::paintEvent(event);
}


void LabelItem::onRenameActionTriggered()
{
    QString oldLabelName = m_nameLabel->text();
    bool ok;

    // 创建 QInputDialog 并清除样式
    QInputDialog dialog(nullptr);  // 父窗口设为 nullptr
    dialog.setWindowTitle("重命名标签");
    dialog.setLabelText("请输入新标签名：");
    dialog.setTextValue(oldLabelName);
    dialog.setInputMode(QInputDialog::TextInput);

    // 清除样式表，使用系统默认样式
    dialog.setStyleSheet("");

    // 执行对话框
    ok = dialog.exec() == QDialog::Accepted;
    QString newLabelName = dialog.textValue();

    if (!ok || newLabelName.isEmpty() || newLabelName == oldLabelName) {
        return;
    }

    emit renameRequested(m_labelId, newLabelName);
}


void LabelItem::onChangeLineActionTriggered()
{
    QString oldRowStr = m_rowLabel->text();
    oldRowStr = oldRowStr.mid(3); // 去掉 "行: " 前缀
    bool ok;

    // 创建 QInputDialog 并清除样式
    QInputDialog dialog(nullptr);  // 父窗口设为 nullptr
    dialog.setWindowTitle("修改行号");
    dialog.setLabelText("请输入新的行号：");
    dialog.setTextValue(oldRowStr);
    dialog.setInputMode(QInputDialog::TextInput);

    // 清除样式表，使用系统默认样式
    dialog.setStyleSheet("");

    // 执行对话框
    ok = dialog.exec() == QDialog::Accepted;
    QString newRowStr = dialog.textValue();

    if (!ok || newRowStr.isEmpty() || newRowStr == oldRowStr) {
        return;
    }

    // 验证输入格式
    QRegularExpression re("^\\d+$"); // 匹配单个数字
    if (!re.match(newRowStr).hasMatch()) {
        // 输入格式不正确，显示错误消息
        QMessageBox::warning(nullptr, "输入错误", "请输入有效的行号（单个数字）。");
        return;
    }

    emit changeLineRequested(m_labelId, newRowStr.toInt());
}

void LabelItem::onThemeChanged(ThemeManager::Theme newTheme)
{
    if (newTheme == ThemeManager::Theme::Dark) {
        setDarkTheme();
    }
    else {
        setLightTheme();
    }
}


void LabelItem::setupUI() {
    setAttribute(Qt::WA_Hover, true);
    setMouseTracking(true);

    m_mainLayout = new QHBoxLayout(this);
    m_mainLayout->setContentsMargins(12, 8, 12, 8);
    m_mainLayout->setSpacing(8);

    // 创建名称标签
    m_nameLabel = new QLabel(this);
    m_nameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    QFont nameFont = m_nameLabel->font();
    nameFont.setPointSize(11);
    nameFont.setWeight(QFont::Medium);
    m_nameLabel->setFont(nameFont);
    m_nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    m_nameLabel->setAttribute(Qt::WA_TransparentForMouseEvents);  // 让鼠标事件穿

    // 创建行号标签
    m_rowLabel = new QLabel(this);
    m_rowLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    QFont timestampFont = m_rowLabel->font();
    timestampFont.setPointSize(10);
    m_rowLabel->setFont(timestampFont);
    m_rowLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);

    // 创建删除按钮
    m_deleteBtn = new QPushButton("×", this);
    m_deleteBtn->setFixedSize(20, 20);
    m_deleteBtn->setStyleSheet(R"(
        QPushButton {
            background-color: transparent;
            border: none;
            color: #95A5A6;
            font-size: 16px;
            font-weight: bold;
            border-radius: 10px;
        }
        QPushButton:hover {
            background-color: #FF5252;
            color: #FFFFFF;
        }
    )");
    m_deleteBtn->setCursor(Qt::PointingHandCursor);
    m_deleteBtn->hide(); // 默认隐藏

    // 连接删除按钮信号
    connect(m_deleteBtn, &QPushButton::clicked, this, [this]() {
        emit deleteRequested(m_labelId);
        });

    // 添加到布局
    m_mainLayout->addWidget(m_nameLabel, 1);
    m_mainLayout->addWidget(m_rowLabel, 0);
    m_mainLayout->addWidget(m_deleteBtn, 0);

    setLayout(m_mainLayout);
    setCursor(Qt::PointingHandCursor);
    setMinimumHeight(42);

    // 初始化右键菜单
    m_contextMenu = new QMenu(this);
    m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #FFFFFF;
            border: 1px solid #E1E5E9;
            border-radius: 6px;
            padding: 4px;
            color: #495057;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #E7F3FF;
            color: #4A90E2;
        }
        QMenu::item:disabled {
            color: #ADB5BD;
        }
        QMenu::separator {
            height: 1px;
            background-color: #E9ECEF;
            margin: 4px 8px;
        }
    )");

    // 添加菜单项
    m_renameAction = new QAction("重命名标签", this);
    connect(m_renameAction, &QAction::triggered, this, &LabelItem::onRenameActionTriggered);
    m_contextMenu->addAction(m_renameAction);

    m_changeLineAction = new QAction("修改行号", this);
    connect(m_changeLineAction, &QAction::triggered, this, &LabelItem::onChangeLineActionTriggered);
    m_contextMenu->addAction(m_changeLineAction);
}

LabelList::LabelList(QWidget* parent)
    : QWidget(parent)
{
    setupUI();

    // ===== 关键修复：手动应用当前主题 =====
    // 因为 ThemeManager 在构造时已经发射过 themeChanged 信号
    // 但那时 LabelList 还没连接，所以需要手动应用一次
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
    if (currentTheme == ThemeManager::Theme::Dark) {
        setDarkTheme();
    }
    else {
        setLightTheme();
    }
}

void LabelList::setDarkTheme()
{
    // 设置标题样式
    m_titleLabel->setStyleSheet(R"(
        QLabel {
            background-color: #4A90E2;
            color: #FFFFFF;
            font-size: 14px;
            font-weight: 600;
            padding: 10px;
            border: none;
            border-bottom: 1px solid #357ABD;
        }
    )");

    // 设置容器背景色
    m_containerWidget->setStyleSheet("background-color: #252526;");

    // 设置滚动条深色样式
    m_scrollArea->setStyleSheet(R"(
        QScrollArea {
            background-color: transparent;
            border: none;
        }
        QScrollBar:vertical {
            background-color: #2D2D30;
            width: 10px;
            margin: 0px;
            border-radius: 5px;
            border: 1px solid #3E3E42;
        }
        QScrollBar::handle:vertical {
            background-color: #5A5A5A;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background-color: #6B6B6B;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    )");

    // 更新所有子项的主题
    for (LabelItem* item : m_items) {
        item->setDarkTheme();
    }

    update();
}

void LabelList::setLightTheme()
{
    // 设置标题样式
    m_titleLabel->setStyleSheet(R"(
        QLabel {
            background-color: #4A90E2;
            color: #FFFFFF;
            font-size: 14px;
            font-weight: 600;
            padding: 10px;
            border: none;
            border-bottom: 1px solid #357ABD;
        }
    )");

    // 设置容器背景色
    m_containerWidget->setStyleSheet("background-color: #FFFFFF;");

    // 设置滚动条浅色样式
    m_scrollArea->setStyleSheet(R"(
        QScrollArea {
            background-color: transparent;
            border: none;
        }
        QScrollBar:vertical {
            background-color: #F8F9FA;
            width: 10px;
            margin: 0px;
            border-radius: 5px;
        }
        QScrollBar::handle:vertical {
            background-color: #CED4DA;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background-color: #ADB5BD;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    )");

    // 更新所有子项的主题
    for (LabelItem* item : m_items) {
        item->setLightTheme();
    }

    update();
}

void LabelList::onThemeChanged(ThemeManager::Theme newTheme)
{
    if (newTheme == ThemeManager::Theme::Dark) {
        setDarkTheme();
    }
    else {
        setLightTheme();
    }
}

void LabelList::setupUI()
{
    // 创建主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);

    // 创建标题标签
    m_titleLabel = new QLabel("书签", this);
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setStyleSheet(R"(
        QLabel {
            background-color: #4A90E2;
            color: #FFFFFF;
            font-size: 14px;
            font-weight: 600;
            padding: 10px;
            border: none;
            border-bottom: 1px solid #357ABD;
        }
    )");
    m_titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 创建滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setFrameShape(QFrame::NoFrame);
    m_scrollArea->setStyleSheet(R"(
        QScrollArea {
            background-color: transparent;
            border: none;
        }
        QScrollBar:vertical {
            background-color: #F8F9FA;
            width: 10px;
            margin: 0px;
            border-radius: 5px;
        }
        QScrollBar::handle:vertical {
            background-color: #CED4DA;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background-color: #ADB5BD;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
    )");

    // 创建容器部件和布局
    m_containerWidget = new QWidget();
    m_containerWidget->setStyleSheet("background-color: #FFFFFF;");
    m_containerLayout = new QVBoxLayout(m_containerWidget);
    m_containerLayout->setContentsMargins(2, 6, 2, 6);
    m_containerLayout->setSpacing(5);
    m_containerLayout->addStretch(); // 添加弹簧，使项目从顶部开始排列

    m_containerWidget->setLayout(m_containerLayout);
    m_scrollArea->setWidget(m_containerWidget);

    // 添加滚动区域到主布局
    mainLayout->addWidget(m_titleLabel);
    mainLayout->addWidget(m_scrollArea);
    setLayout(mainLayout);

    connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged, this, &LabelList::onThemeChanged);
}

void LabelList::addItem(const QString& name, int row)
{
    LabelItem* item = new LabelItem(name, row, m_containerWidget);
    addItem(item);
}

void LabelList::addItem(const QString& name, const QString& rowStr)
{
    LabelItem* item = new LabelItem(name, rowStr, m_containerWidget);
    addItem(item);
}

void LabelList::addItem(LabelItem* item)
{
    if (!item) return;

    // 连接点击信号
    connect(item, &LabelItem::clicked, this, &LabelList::onItemClicked);

    // 插入到弹簧之前
    int index = m_containerLayout->count() - 1;
    m_containerLayout->insertWidget(index, item);
    m_items.append(item);
}

void LabelList::insertItem(int index, const QString& name, int row)
{
    LabelItem* item = new LabelItem(name, row, m_containerWidget);
    insertItem(index, item);
}

void LabelList::insertItem(int index, const QString& name, const QString& rowStr)
{
    LabelItem* item = new LabelItem(name, rowStr, m_containerWidget);
    insertItem(index, item);
}

void LabelList::insertItem(int index, LabelItem* item)
{
    if (!item || index < 0 || index > m_items.count()) return;

    // 连接点击信号
    connect(item, &LabelItem::clicked, this, &LabelList::onItemClicked);

    // 插入到布局
    m_containerLayout->insertWidget(index, item);
    m_items.insert(index, item);
}

void LabelList::removeItem(int index)
{
    if (index < 0 || index >= m_items.count()) return;

    LabelItem* item = m_items.takeAt(index);
    m_containerLayout->removeWidget(item);
    item->deleteLater();
}

void LabelList::removeItem(LabelItem* item)
{
    if (!item) return;

    int index = m_items.indexOf(item);
    if (index >= 0) {
        removeItem(index);
    }
}

void LabelList::removeItemByName(const QString& name)
{
    int index = findItemByName(name);
    if (index >= 0) {
        removeItem(index);
    }
}

void LabelList::clear()
{
    // 删除所有项目
    while (!m_items.isEmpty()) {
        LabelItem* item = m_items.takeFirst();
        m_containerLayout->removeWidget(item);
        item->deleteLater();
    }
}

LabelItem* LabelList::itemAt(int index) const
{
    if (index >= 0 && index < m_items.count()) {
        return m_items.at(index);
    }
    return nullptr;
}

int LabelList::findItemByName(const QString& name) const
{
    for (int i = 0; i < m_items.count(); ++i) {
        if (m_items.at(i)->getName() == name) {
            return i;
        }
    }
    return -1;
}

void LabelList::onItemClicked(int row)
{
    emit itemClicked(row);
}